package com.shop.cloud.service.hongfu.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shop.cloud.JPush.MsgPushUtils;
import com.shop.cloud.common.mybatis.BaseService;
import com.shop.cloud.common.mybatis.MybatisDao;
import com.shop.cloud.dao.hongfu.DistributionInstallDao;
import com.shop.cloud.dao.hongfu.GoodsImageDao;
import com.shop.cloud.dao.hongfu.GoodsOrderDao;
import com.shop.cloud.dao.hongfu.OrderProductDetailDao;
import com.shop.cloud.domain.hongfu.BalanceHistory;
import com.shop.cloud.domain.hongfu.DistributionInstall;
import com.shop.cloud.domain.hongfu.Goods;
import com.shop.cloud.domain.hongfu.GoodsImage;
import com.shop.cloud.domain.hongfu.GoodsOrder;
import com.shop.cloud.domain.hongfu.GoodsProduct;
import com.shop.cloud.domain.hongfu.InsGoods;
import com.shop.cloud.domain.hongfu.Message;
import com.shop.cloud.domain.hongfu.OrderAddressHistory;
import com.shop.cloud.domain.hongfu.OrderProductDetail;
import com.shop.cloud.domain.hongfu.Shop;
import com.shop.cloud.domain.hongfu.ShopImage;
import com.shop.cloud.domain.hongfu.User;
import com.shop.cloud.domain.hongfu.UserAddress;
import com.shop.cloud.service.hongfu.IBalanceHistoryService;
import com.shop.cloud.service.hongfu.IDistributionMsgService;
import com.shop.cloud.service.hongfu.IGoodsOrderService;
import com.shop.cloud.service.hongfu.IGoodsProductService;
import com.shop.cloud.service.hongfu.IGoodsService;
import com.shop.cloud.service.hongfu.IMessageService;
import com.shop.cloud.service.hongfu.IOrderAddressHistoryService;
import com.shop.cloud.service.hongfu.IOrderProductDetailService;
import com.shop.cloud.service.hongfu.IShopImageService;
import com.shop.cloud.service.hongfu.IShopService;
import com.shop.cloud.service.hongfu.IUserAddressService;
import com.shop.cloud.service.hongfu.IUserService;
import com.shop.cloud.service.system.ISysUserService;
import com.shop.cloud.util.Page;

import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;

/**
 * goods_order
 */
@Transactional
@Service("goodsOrderService")
public class GoodsOrderService extends BaseService<GoodsOrder> implements IGoodsOrderService{
    
    @Autowired
	private GoodsOrderDao goodsOrderDao;
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private IGoodsService goodsService;
    
    @Autowired
    private IGoodsProductService goodsProductService;
    
    @Autowired
    private IDistributionMsgService distributionMsgService;
    
    @Autowired
    private IMessageService messageService;
    
    @Autowired
    private IShopService shopService;
    
    @Autowired
    private IBalanceHistoryService balanceHistoryService;
    
    @Autowired
    private DistributionInstallDao distributionInstallDao;
    
    @Autowired
    private GoodsImageDao goodsImageDao;
    
    @Autowired
    private IOrderProductDetailService orderProductDetailService;
    
    @Autowired
    private OrderProductDetailDao orderProductDetailDao;
    
    @Autowired
    private IUserAddressService userAddressService;
    
    @Autowired
    private IOrderAddressHistoryService orderAddressHistoryService;
    
    @Autowired
	private ISysUserService sysUserService;
    
    @Autowired
    private IShopImageService shopImageService;

	@Override
	public MybatisDao<GoodsOrder> getEntityDao() {
		return goodsOrderDao;
	}

	@Override
	public int handleplaceAnOrder(GoodsOrder goodsOrder) {
		Long userId = goodsOrder.getUserId();
		//获取当前用户
		User user = userService.get(userId);
		//用户余额
		float userBalance = user.getBalance();
		//用户积分
		int userPoints = user.getPoints();
		//会员卡剩余额度
		float vipBalance = user.getVipBalance().floatValue();
		
		
		//订单号
		String orderNo = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ((int)((Math.random()*9+1)*100000));
		goodsOrder.setOrderNo(orderNo);
		goodsOrder.setCreateTime(new Timestamp((new Date()).getTime()));
		//初始订单总金额或总积分
		float orderAmount = 0;
		//获取订单中商品的信息
		String goods = goodsOrder.getJsonAppMsg();
		try {
			if(StringUtils.isNotEmpty(goods)){
				JSONArray jsonArray = new JSONArray(goods);
				//判断用户余额是否够
				for(int i = 0; i < jsonArray.length(); i ++){
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					
					Long insGoodsId = jsonObject.getLong("goodsId");
					Goods insGoods = goodsService.get(insGoodsId);
					if(insGoods.getStatus() == 3 || insGoods.getStatus() == 4){
						//商品已下架或者已删除
						return 2;
					}
					goodsOrder.setGoodsMall(insGoods.getType());
					goodsOrder.setShopId(insGoods.getShopId());
					
					Long insGoodsProductId = jsonObject.getLong("insGoodsProductId");
					Integer insGoodsNum = jsonObject.getInt("goodsNum");
					GoodsProduct insGoodsProduct = goodsProductService.get(insGoodsProductId);
					if(insGoodsNum > insGoodsProduct.getStock()){
						//商品库存不足
						return 3;
					}
					float thisAmount = 0f;
					int isSpecialPrice = insGoods.getIsSpecialPrice();
					if(isSpecialPrice == 1){
						//特价商品
						thisAmount = insGoods.getSpecialPrice();
					}else{
						//商品价格或者积分
						thisAmount = insGoodsProduct.getPrice();
					}
					
					thisAmount = thisAmount * insGoodsNum;
					orderAmount = orderAmount + thisAmount;
				}
				
				if(goodsOrder.getGoodsMall() != 2){
					goodsOrder.setAmount(orderAmount);
					if(goodsOrder.getGoodsMall()==4){
						if(vipBalance < orderAmount){
							//会员额度已不足
							return  4;
						}
					}else{
						
						if(userBalance < orderAmount){
							//用户余额不够
							return 1;
						}
					}
				}else{
					goodsOrder.setPoints((int)orderAmount);
					if(userPoints < (int)orderAmount){
						//用户积分不够
						return 1;
					}
				}
				
				for(int i = 0; i < jsonArray.length(); i ++){
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					
					OrderProductDetail orderProductDetail = new OrderProductDetail();
					orderProductDetail.setOrderNo(goodsOrder.getOrderNo());
					
					Long insGoodsId = jsonObject.getLong("goodsId");
					Long insGoodsProductId = jsonObject.getLong("insGoodsProductId");
					Integer insGoodsNum = jsonObject.getInt("goodsNum");
					orderProductDetail.setGoodsNum(insGoodsNum);
					//修改商品库存和销量
					Goods insGoods = goodsService.get(insGoodsId);
					if(null != insGoods){
						insGoods.setSoldCount(insGoods.getSoldCount() + insGoodsNum);
						insGoods.setInventory(insGoods.getInventory() - insGoodsNum);
						goodsService.update(insGoods);
						
						orderProductDetail.setGoodsId(insGoods.getId());
					}
					GoodsProduct insGoodsProduct = goodsProductService.get(insGoodsProductId);
					if(null != insGoodsProduct){
						insGoodsProduct.setSoldVolume(insGoodsProduct.getSoldVolume() + insGoodsNum);
						insGoodsProduct.setStock(insGoodsProduct.getStock() - insGoodsNum);
						goodsProductService.update(insGoodsProduct);
						
						float thisAmount = 0f;
						int isSpecialPrice = insGoods.getIsSpecialPrice();
						if(isSpecialPrice == 1){
							//特价商品
							thisAmount = insGoods.getSpecialPrice();
						}else{
							//商品价格或者积分
							thisAmount = insGoodsProduct.getPrice();
						}
						
						orderProductDetail.setGoodsProductId(insGoodsProduct.getId());
						if(insGoods.getType() != 2){
							orderProductDetail.setGoodsAmount(thisAmount);
						}else{
							orderProductDetail.setGoodsPoints((int)(thisAmount));
						}
					}
					orderProductDetail.setCreateTime(new Timestamp((new Date()).getTime()));
					//保存
					orderProductDetailService.insert(orderProductDetail);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		//处理用户收货地址
		Long userAddr = goodsOrder.getUserAddr();
		UserAddress userAddress =  userAddressService.get(userAddr);
		if(null != userAddress){
			Long timestamp = new Date().getTime()/1000;
			timestamp = timestamp + ((int)((Math.random()*9+1)*1));
			OrderAddressHistory orderAddressHistory = new OrderAddressHistory(); 
			orderAddressHistory.setHistoryNo(timestamp);
			orderAddressHistory.setName(userAddress.getName());
			orderAddressHistory.setPhone(userAddress.getPhone());
			orderAddressHistory.setRegionId(userAddress.getRegionId());
			orderAddressHistory.setAddress(userAddress.getAddress());
			//保存订单历史收货地址
			orderAddressHistoryService.insert(orderAddressHistory);
			goodsOrder.setUserAddr(timestamp);
		}
		
		//保存订单
		this.insert(goodsOrder);
		
		//扣除余额或积分
		int goodsMall = goodsOrder.getGoodsMall();
		
		if(goodsMall != 2){
			float amount = goodsOrder.getAmount();
			//获取当前余额
			float balance = user.getBalance();
			
			BigDecimal thisAmount = new BigDecimal(balance);
			BigDecimal useAmount = new BigDecimal(amount);
			
			thisAmount = thisAmount.subtract(useAmount);
			thisAmount = thisAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			user.setBalance(thisAmount.floatValue());
			if(goodsMall == 4){
				//处理返利商品购买后操作
				float rebateAmount = user.getTotalConsumeAmount(); //返利商城历史消费金额
				BigDecimal rbAmount = new BigDecimal(rebateAmount);
				rbAmount = rbAmount.add(useAmount);
				rbAmount = rbAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
				user.setTotalConsumeAmount(rbAmount.floatValue());
				float remainAmount = user.getRemainConsumeAmount(); //返利中剩余消费金额
				BigDecimal rmAmount = new BigDecimal(remainAmount);
				rmAmount = rmAmount.add(useAmount);
				rmAmount = rmAmount.setScale(2, BigDecimal.ROUND_HALF_DOWN);
				user.setRemainConsumeAmount(rmAmount.floatValue());
				
				//减掉会员额度
				user.setVipBalance(user.getVipBalance()-goodsOrder.getAmount().intValue());
			}
			
			BalanceHistory balanceHistory = new BalanceHistory();
			balanceHistory.setUserId(userId);
			if(goodsMall == 1){//鸿福商品
				balanceHistory.setType(2);
			}
			if(goodsMall == 3){//旅游商品
				balanceHistory.setType(4);
			}
			if(goodsMall == 4){//返利商品
				balanceHistory.setType(24);
			}
			balanceHistory.setAmount(amount);
			balanceHistory.setOrderNo(goodsOrder.getOrderNo());
			balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
			balanceHistory.setRemark(user.getNickname()+"购买商品,消费"+amount+"余额");
			balanceHistory.setUserLevel(0);
			//创建流水
			balanceHistoryService.insert(balanceHistory);
		}else{
			int point = goodsOrder.getPoints();
			//获取当前积分
			int points = user.getPoints();
			user.setPoints(points-point);
			
			BalanceHistory balanceHistory = new BalanceHistory();
			balanceHistory.setUserId(userId);
			balanceHistory.setType(3);
			balanceHistory.setCredits(point);
			balanceHistory.setOrderNo(goodsOrder.getOrderNo());
			balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
			balanceHistory.setRemark(user.getNickname()+"购买商品,消费"+point+"积分");
			balanceHistory.setUserLevel(0);
			//创建流水
			balanceHistoryService.insert(balanceHistory);
		}
		//保存修改
		userService.update(user);
		
		//消费金额 需判断分销设置
		if(goodsMall == 1 || goodsMall == 3){
			try {
				distributionMsgService.handleGoodsGetMoney(goodsOrder.getOrderNo());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	
		Shop shop = shopService.get(goodsOrder.getShopId());
		if(null != shop){
			//生成消息
			Message message = new Message();
			message.setUserId(goodsOrder.getUserId());
			message.setType(2);
			message.setContent("您在["+ shop.getName() +"]下的订单已支付成功。");
			message.setCreateTime(new Timestamp(new Date().getTime()));
			message.setOrderId(goodsOrder.getOrderNo());
			message.setTitle("您的订单支付成功");
			message.setRemark("订单支付成功");
			//推送消息
			messageService.insert(message);
			
			//极光推送
			try {
				MsgPushUtils.addJPush(message.getContent(), goodsOrder.getUserId().toString());
			} catch (APIConnectionException e) {
				e.printStackTrace();
			} catch (APIRequestException e) {
				e.printStackTrace();
			}
		}else{
			//生成消息
			Message message = new Message();
			message.setUserId(goodsOrder.getUserId());
			message.setType(2);
			message.setContent("您的订单已支付成功。");
			message.setCreateTime(new Timestamp(new Date().getTime()));
			message.setOrderId(goodsOrder.getOrderNo());
			message.setTitle("您的订单支付成功");
			message.setRemark("订单支付成功");
			//推送消息
			messageService.insert(message);
			
			//极光推送
			try {
				MsgPushUtils.addJPush(message.getContent(), goodsOrder.getUserId().toString());
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		
		return 0;
	}

	@Override
	public Page<GoodsOrder> handleOrderList(GoodsOrder goodsOrder) {
		//分页请求参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", goodsOrder.getUserId());
		params.put("shopId", goodsOrder.getShopId());
		params.put("goodsMall", goodsOrder.getGoodsMall());
		params.put("orderNo", goodsOrder.getOrderNo());
		params.put("startTime", goodsOrder.getStartTime());
		params.put("endTime", goodsOrder.getEndTime());
		params.put("takeGoodsType", goodsOrder.getTakeGoodsType());
		params.put("status", goodsOrder.getStatus());
		params.put("orderBy", goodsOrder.getOrderBy());
		if(null != goodsOrder.getStatus() && goodsOrder.getStatus() == 5){
			int[] statusIns = new int[2];
			statusIns[0] = 3;
			statusIns[1] = 4;
			params.put("statusIns", statusIns);
		}
		
		long count = goodsOrderDao.findOrderByPageCount(params);
		int pageIndex = goodsOrder.getPageIndex_();
		int pageSize = 20;
		if(null != goodsOrder.getPageSize_()){
			pageSize = goodsOrder.getPageSize_();
		}
		Page<GoodsOrder> page = new Page<GoodsOrder>(pageIndex,pageSize);
		int limitStart = (pageIndex - 1) * pageSize;
		params.put("limitStart", limitStart);
		
		int limitEnd = pageSize;
		params.put("limitEnd", limitEnd);
		
		List<GoodsOrder> thisData = goodsOrderDao.findOrderByPage(params);
		if(null != thisData && thisData.size() > 0){
			for(GoodsOrder order : thisData){
				order = this.handleThisGoodsOrder(order);
			}
		}
		page.setData(thisData);
		page.setTotalCount(count);
		
		return page;
	}

	@Override
	public GoodsOrder handleOrderDetail(GoodsOrder goodsOrder) {
		//获取数据库中数据
		GoodsOrder insData = goodsOrderDao.findOrderDetail(goodsOrder);
		insData = this.handleThisGoodsOrder(insData);
		if(insData.getTakeGoodsType() == 1){
			Long takeShopId = insData.getTakeShopId();
			Shop takeShop = shopService.get(takeShopId);
			
			ShopImage tmp = new ShopImage();
			tmp.setShopId(takeShopId);
			List<ShopImage> tmps = shopImageService.find(tmp);
			if(null != tmps && tmps.size() > 0){
				takeShop.setIcon(tmps.get(0).getImage());
			}
			
			insData.setGetShopMsg(takeShop);
		}
		ShopImage shopImage = new ShopImage();
		shopImage.setShopId(insData.getShopId());
		List<ShopImage> list = shopImageService.find(shopImage);
		if(null != list && list.size() > 0){
			insData.setShopImages(list.get(0).getImage());
		}
		
		return insData;
	}
	
	private GoodsOrder handleThisGoodsOrder(GoodsOrder insData){
		
		User orderUser = userService.get(insData.getUserId());
		insData.setOrderUser(orderUser);
		Shop orderShop = shopService.get(insData.getShopId());
		insData.setOrderShop(orderShop);
		OrderAddressHistory oah = new OrderAddressHistory();
		oah.setHistoryNo(insData.getUserAddr());
		List<OrderAddressHistory> thisList = orderAddressHistoryService.find(oah);
		if(null != thisList && thisList.size() > 0){
			insData.setUserAddress(thisList.get(0));
		}
		
		//订单中商品信息列表
		List<InsGoods> goodsList = new ArrayList<InsGoods>();
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderNo", insData.getOrderNo());
		List<OrderProductDetail> detailList = orderProductDetailDao.getThisByOrderNo(params);
		
		if(null != detailList && detailList.size() > 0){
			for(int i = 0; i < detailList.size(); i ++){
				InsGoods insGoodsData = new InsGoods();
				
				Long insGoodsId = detailList.get(i).getGoodsId();
				Long insGoodsProductId = detailList.get(i).getGoodsProductId();
				Integer insGoodsNum = detailList.get(i).getGoodsNum();
				
				Goods insGoods = goodsService.get(insGoodsId);
				GoodsProduct insGoodsProduct = goodsProductService.get(insGoodsProductId);
				//订单中价格
				if(insGoods.getType() != 2){
					float insGoodsPrice = detailList.get(i).getGoodsAmount();
					insGoods.setPrice(insGoodsPrice);
					insGoodsProduct.setPrice(insGoodsPrice);
				}else{
					int insGoodsPoints = detailList.get(i).getGoodsPoints();
					insGoods.setPrice(new Float(insGoodsPoints));
					insGoodsProduct.setPrice(new Float(insGoodsPoints));
				}
				
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("goodsID", insGoodsId);
				List<GoodsImage> goodsImages = goodsImageDao.findByGoodsID(param);
				insGoods.setGoodsImages(goodsImages);
				
				insGoodsData.setGoods(insGoods);
				insGoodsData.setGoodsProduct(insGoodsProduct);
				insGoodsData.setNum(insGoodsNum);
				
				if(insGoods.getOpenDistribution() == 1){
					DistributionInstall distributionInstall = distributionInstallDao.getByTypeAndID(insGoods.getId());
					
					if(null != distributionInstall){
						String distributionString = distributionInstall.getDistriSetting();
						if(StringUtils.isNotEmpty(distributionString)){
							try {
								JSONArray jsonArray1 = new JSONArray(distributionString);
								for(int j = 0; j < jsonArray1.length(); j ++){
									JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
									String descName = jsonObject1.getString("desc_name");
									if(StringUtils.isNotEmpty(descName) && "一级".equals(descName)){
										insGoodsData.setDistributeValueOne(jsonObject1.getString("desc_value"));
									}
									if(StringUtils.isNotEmpty(descName) && "二级".equals(descName)){
										insGoodsData.setDistributeValueTwo(jsonObject1.getString("desc_value"));
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}
				}
				goodsList.add(insGoodsData);
			}
		}
		insData.setInsGoods(goodsList);
		
		return insData;
	}

	@Override
	public Integer handleOrderStatus(GoodsOrder goodsOrderParams) {
		GoodsOrder goodsOrder = this.get(goodsOrderParams.getId());
		goodsOrder.setStatus(goodsOrderParams.getStatus());
		//获取店铺信息
		Shop shop = shopService.get(goodsOrder.getShopId());
		
		if(null != shop){
			int status = goodsOrder.getStatus();
			if(status == 2){
				//生成消息
				Message message = new Message();
				message.setUserId(goodsOrder.getUserId());
				message.setType(2);
				message.setContent("您在["+ shop.getName() +"]下的订单已发货。");
				message.setCreateTime(new Timestamp(new Date().getTime()));
				message.setOrderId(goodsOrder.getOrderNo());
				message.setTitle("您的订单已发货");
				message.setRemark("订单已发货");
				//推送消息
				messageService.insert(message);
				
				//极光推送
				try {
					MsgPushUtils.addJPush(message.getContent(), goodsOrder.getUserId().toString());
				} catch (APIConnectionException e) {
					e.printStackTrace();
				} catch (APIRequestException e) {
					e.printStackTrace();
				}
			}
			if(status == 3){
				//生成消息
				Message message = new Message();
				message.setUserId(goodsOrder.getUserId());
				message.setType(2);
				message.setContent("您在["+ shop.getName() +"]下的订单已完成。");
				message.setCreateTime(new Timestamp(new Date().getTime()));
				message.setOrderId(goodsOrder.getOrderNo());
				message.setTitle("您的订单已完成");
				message.setRemark("订单已完成");
				//推送消息
				messageService.insert(message);
				
				//极光推送
				try {
					MsgPushUtils.addJPush(message.getContent(), goodsOrder.getUserId().toString());
				} catch (APIConnectionException e) {
					e.printStackTrace();
				} catch (APIRequestException e) {
					e.printStackTrace();
				}
			}
			if(status == 4){
				//生成消息
				Message message = new Message();
				message.setUserId(goodsOrder.getUserId());
				message.setType(2);
				message.setContent("您在["+ shop.getName() +"]下的订单商家拒绝接单，理由：缺货。");
				message.setCreateTime(new Timestamp(new Date().getTime()));
				message.setOrderId(goodsOrder.getOrderNo());
				message.setTitle("您的订单已取消");
				message.setRemark("订单已取消");
				//推送消息
				messageService.insert(message);
				
				//极光推送
				try {
					MsgPushUtils.addJPush(message.getContent(), goodsOrder.getUserId().toString());
				} catch (APIConnectionException e) {
					e.printStackTrace();
				} catch (APIRequestException e) {
					e.printStackTrace();
				}
				
				int goodsMall = goodsOrder.getGoodsMall();
				//退款
				User user = userService.get(goodsOrder.getUserId());
				if(goodsMall != 2){
					user.setBalance(user.getBalance() + goodsOrder.getAmount());
				}else{
					user.setPoints(user.getPoints() + goodsOrder.getPoints());
				}
				userService.update(user);
				//修改商品库存和销量
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("orderNo", goodsOrder.getOrderNo());
				List<OrderProductDetail> detailList = orderProductDetailDao.getThisByOrderNo(params);
				if(null != detailList && detailList.size() > 0){
					for(int i = 0; i < detailList.size(); i ++){
						Long goosId = detailList.get(i).getGoodsId();
						Long insGoodsProductId = detailList.get(i).getGoodsProductId();
						int insGoodsNum = detailList.get(i).getGoodsNum();
						
						Goods insGoods = goodsService.get(goosId);
						insGoods.setSoldCount(insGoods.getSoldCount() - insGoodsNum);
						insGoods.setInventory(insGoods.getInventory() + insGoodsNum);
						goodsService.update(insGoods);
						
						GoodsProduct insGoodsProduct = goodsProductService.get(insGoodsProductId);
						insGoodsProduct.setSoldVolume(insGoodsProduct.getSoldVolume() - insGoodsNum);
						insGoodsProduct.setStock(insGoodsProduct.getStock() + insGoodsNum);
						goodsProductService.update(insGoodsProduct);
					}
				}
				
				
				//处理财务流水
				BalanceHistory balanceHistory = new BalanceHistory();
				balanceHistory.setUserId(goodsOrder.getUserId());
				if(goodsMall == 1){
					balanceHistory.setType(16);
					balanceHistory.setAmount(goodsOrder.getAmount());
				}
				if(goodsMall == 2){
					balanceHistory.setType(18);
					balanceHistory.setCredits(goodsOrder.getPoints());
				}
				if(goodsMall == 3){
					balanceHistory.setType(17);
					balanceHistory.setAmount(goodsOrder.getAmount());
				}
				balanceHistory.setOrderNo(goodsOrder.getOrderNo());
				balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
				balanceHistory.setRemark("商品退款");
				//创建流水
				balanceHistoryService.insert(balanceHistory);
			}
		}
		
		int resultInt = this.update(goodsOrder);
		
		return resultInt;
	}

	@Override
	public Page<GoodsOrder> handleMOrderList(GoodsOrder goodsOrder) {
		//获取权限信息
		Map<String, Object> userParams = sysUserService.handleUserAuthority(goodsOrder.getUserId());
		if(null != userParams && userParams.size() > 0){
			int authority = (int)userParams.get("authority");
			if(authority == 2){
				Long[] shops = (Long[]) userParams.get("shops");
				goodsOrder.setShops(shops);
			}
		}
		
		//分页请求参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("shopId", goodsOrder.getShopId());
		params.put("goodsMall", goodsOrder.getGoodsMall());
		params.put("orderNo", goodsOrder.getOrderNo());
		params.put("startTime", goodsOrder.getStartTime());
		params.put("endTime", goodsOrder.getEndTime());
		params.put("takeGoodsType", goodsOrder.getTakeGoodsType());
		params.put("status", goodsOrder.getStatus());
		params.put("shops", goodsOrder.getShops());
		params.put("orderBy", goodsOrder.getOrderBy());
		
		long count = goodsOrderDao.findOrderByPageCount(params);
		int pageIndex = goodsOrder.getPageIndex_();
		int pageSize = 20;
		if(null != goodsOrder.getPageSize_()){
			pageSize = goodsOrder.getPageSize_();
		}
		Page<GoodsOrder> page = new Page<GoodsOrder>(pageIndex,pageSize);
		int limitStart = (pageIndex - 1) * pageSize;
		params.put("limitStart", limitStart);
		
		int limitEnd = pageSize;
		params.put("limitEnd", limitEnd);
		
		List<GoodsOrder> thisData = goodsOrderDao.findOrderByPage(params);
		if(null != thisData && thisData.size() > 0){
			for(GoodsOrder order : thisData){
				order = this.handleThisGoodsOrder(order);
			}
		}
		page.setData(thisData);
		page.setTotalCount(count);
		
		return page;
	}
    
}